package per.dg.keepalive.servicebug

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.util.Log
import per.dg.keepalive.R

/**
 * 适合8.0（26）以下
 */

class KeepLiveService : Service() {

    companion object{
        val NOTIFICATION_ID = 0x11

        class InnerService : Service(){

            override fun onCreate() {
                super.onCreate();
                //发送与KeepLiveService中ID相同的Notification，然后将其取消并取消自己的前台显示
                var builder : Notification.Builder  = Notification.Builder(this);
                builder.setSmallIcon(R.mipmap.ic_launcher);

                startForeground(NOTIFICATION_ID, builder.build());
                Handler().postDelayed(object : Runnable {
                    override fun run() {
                        stopForeground(true);
                        var manager : NotificationManager  =
                            getSystemService(NOTIFICATION_SERVICE) as NotificationManager;
                        manager.cancel(NOTIFICATION_ID);
                        stopSelf();
                    }
                }, 100)

            }

            override fun onBind(intent: Intent?): IBinder? {
                return null;
            }
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
//        throw UnsupportedOperationException("Not yet implemented");
        return null
    }

    override fun onCreate() {
        super.onCreate();
        //API 18以下，直接发送Notification并将其置为前台
        if (Build.VERSION.SDK_INT <Build.VERSION_CODES.JELLY_BEAN_MR2) {
            startForeground(NOTIFICATION_ID, Notification());
        } else {
            //API 18以上，发送Notification并将其置为前台后，启动InnerService
            var builder : Notification.Builder  = Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_launcher);

            startForeground(NOTIFICATION_ID, builder.build());
            startService(Intent(this, InnerService::class.java));

        }
    }

}